package com.ndood.admin.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ndood.admin.core.util.JPAUtil;
import com.ndood.admin.pojo.comm.dto.DataTableDto;
import com.ndood.admin.pojo.system.DepartmentPo;
import com.ndood.admin.pojo.system.RegionPo;
import com.ndood.admin.pojo.system.RolePo;
import com.ndood.admin.pojo.system.UserPo;
import com.ndood.admin.pojo.system.dto.UserDto;
import com.ndood.admin.pojo.system.query.UserQuery;
import com.ndood.admin.repository.system.RegionRepository;
import com.ndood.admin.repository.system.UserRepository;
import com.ndood.admin.repository.system.manager.UserRepositoryManager;
import com.ndood.admin.service.system.SystemUserService;

/**
 * 用户模块业务类
 * @author ndood
 */
@Service
public class SystemUserServiceImpl implements SystemUserService{
	
	@Autowired
	private UserRepository userDao;
	
	@Autowired
	private UserRepositoryManager userRepositoryManager;
	
	@Autowired
	private RegionRepository regionDao;

	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public String addUser(UserDto dto) throws Exception {
		// Step1: 补充相关默认字段
		dto.setCreateTime(new Date());
		dto.setUpdateTime(new Date());
		if(dto.getPassword()==null) {
			dto.setPassword(passwordEncoder.encode("123456"));
		}else {
			dto.setPassword(passwordEncoder.encode(dto.getPassword()));
		}

		UserPo po = new UserPo();
		if(dto.getProvinceId()!=null) {
			RegionPo province = regionDao.findBySid(dto.getProvinceId());
			po.setProvince(province);
		}
		
		if(dto.getCityId()!=null) {
			RegionPo city = regionDao.findBySid(dto.getCityId());
			po.setCity(city);
		}
		
		if(dto.getDistrictId()!=null) {
			RegionPo district = regionDao.findBySid(dto.getDistrictId());
			po.setDistrict(district);
		}
		
		if(dto.getDeptId()!=null) {
			DepartmentPo department = new DepartmentPo();
			department.setId(dto.getDeptId());
			po.setDepartment(department);
		}
		
		if(dto.getRoleIds()!=null) {
			List<RolePo> roles = new ArrayList<RolePo>();
			for (Integer roleId : dto.getRoleIds()) {
				RolePo role = new RolePo();
				role.setId(roleId);
				roles.add(role);
			}
			po.setRoles(roles);
		}
		
		JPAUtil.childToFather(dto, po);
		
		// Step2: 保存用户信息
		UserPo userPo = userDao.save(po);
		return userPo.getUserId();
	}

	@Override
	public void batchDeleteUser(Integer[] ids) {
		// userDao.deleteByIdByIds(Arrays.asList(ids));
		for (Integer id : ids) {
			userDao.deleteById(id);
		}
	}

	@Override
	public void updateUser(UserDto dto) throws Exception {
		// Step1: 判断是否更新密码
		UserPo po = userDao.findById(dto.getId()).get();
		String newPassword = dto.getPassword();
		if(!StringUtils.isEmpty(newPassword)){
			if(!passwordEncoder.matches(po.getPassword(), newPassword)){
				dto.setPassword(passwordEncoder.encode(newPassword));
			}
		}
		dto.setUpdateTime(new Date());
		JPAUtil.childToFather(dto, po);
		
		RegionPo province = regionDao.findBySid(dto.getProvinceId());
		po.setProvince(province);
		
		RegionPo city = regionDao.findBySid(dto.getCityId());
		po.setCity(city);
		
		RegionPo district = regionDao.findBySid(dto.getDistrictId());
		po.setDistrict(district);
		
		DepartmentPo department = new DepartmentPo();
		department.setId(dto.getDeptId());
		po.setDepartment(department);
		
		List<RolePo> roles = new ArrayList<RolePo>();
		for (Integer roleId : dto.getRoleIds()) {
			RolePo role = new RolePo();
			role.setId(roleId);
			roles.add(role);
		}
		po.setRoles(roles);
		
		// Step2: 更新时间
		userDao.save(po);
	}
	
	@Override
	public UserDto getUser(Integer id) throws Exception {
		// Step1: 获取用户信息时不能暴露密码
		UserPo po = userDao.findById(id).get();
		po.setPassword(null);
		
		UserDto dto = new UserDto();
		JPAUtil.fatherToChild(po, dto);
		
		dto.setProvince(po.getProvince()==null?null:po.getProvince());
		dto.setCity(po.getCity()==null?null:po.getCity());
		dto.setDistrict(po.getDistrict()==null?null:po.getDistrict());
		dto.setDeptId(po.getDepartment()==null?null:po.getDepartment().getId());
		dto.setRoles(po.getRoles());
		return dto;
	}

	/**
	 * 分页查询用户信息，采用jpa的dto形式
	 */
	public DataTableDto pageUserList(UserQuery query) throws Exception{
		Page<UserDto> page = userRepositoryManager.pageUserList(query);
		return new DataTableDto(page.getContent(), page.getTotalElements());
	}

}